<template>
  <MyCalendar @date-change="dateChange" />
  <div class="data-list">
    <transition-group name="deletable-item" tag="div">
      <div class="data" v-for="data in todayData" :key="data.id">
        <div>
          <span class="value">{{ data.typeName }}</span>
        </div>
        <div>
          <span class="value">{{ data.value }}</span>
        </div>
        <div>
          <span class="value">{{ data.typeUnit }}</span>
        </div>
        <i @click="deleteDataByID(data.id)" class="del-btn el-icon-error" />
      </div>
    </transition-group>
  </div>
  <div class="plus-btn" @click="changeVisible(true)">
    <i class="el-icon-circle-plus" />
  </div>
  <el-dialog v-model="visible" width="90%">
    <el-form :model="dataForm" ref="dataFormRef" :rules="rules">
      <el-form-item label="类别" prop="typeName">
        <el-select
          value-key="name"
          v-model="formBindType"
          placeholder="请选择类型"
          @change="typeChange"
        >
          <el-option
            v-for="type in allTypes"
            :key="type.id"
            :label="type.name"
            :value="type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input-number v-model="dataForm.value" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitData">新增</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import MyCalendar from "/@/components/MyCalendar.vue";
import { onMounted, reactive, Ref, ref } from "vue";
import {
  addData,
  Data,
  deleteData,
  listDataOneDay,
  listTypes,
  Type,
} from "/@/util/api";
export default {
  name: "Home",
  components: { MyCalendar },
  setup(props, context) {
    // =====日期变化逻辑=====
    let selectedDate = ref(new Date());
    function dateChange(date: Date) {
      console;
      selectedDate.value = date;
      fetchSelectedDateData(date);
    }

    const getDataLogic = { dateChange };

    // =====弹窗弹出逻辑=====
    let visible = ref(false);
    function changeVisible(v: boolean) {
      visible.value = v;
    }
    const dialogLogic = { visible, changeVisible };

    // ============表单验证与提交逻辑==================
    let dataFormRef = ref(null);
    let rules = {
      typeName: [{ required: true, message: "请选择类型", trigger: "change" }],
      value: [{ required: true, message: "请输入值", trigger: "blur" }],
    };
    function submitData() {
      (dataFormRef.value as any).validate((valid: boolean) => {
        if (valid) {
          let today = new Date();
          if (
            selectedDate.value.toLocaleDateString() ==
            today.toLocaleDateString()
          ) {
            dataForm.timestamp = today.getTime();
          } else {
            dataForm.timestamp =
              selectedDate.value.getTime() + 12 * 60 * 60 * 1000;
          }
          dataForm.date = selectedDate.value.toLocaleDateString();
          console.log(dataForm);
          addData(dataForm).then((res) => {
            console.log(res);
            (dataFormRef.value as any).resetFields();
            formBindType.value = null;
            visible.value = false;
            fetchSelectedDateData(selectedDate.value);
          });
        }
      });
    }

    let allTypes: Ref<Array<Type>> = ref([]);
    onMounted(() => {
      getAllTypes();
    });
    function getAllTypes() {
      // 获取所有类型
      let sessionAllTypes = JSON.parse(
        window.sessionStorage.getItem("all-types") || "[]"
      ); // 所有类型
      if (sessionAllTypes.length === 0) {
        listTypes().then((res) => {
          if (res.code === 0) {
            allTypes.value = res.data;
            window.sessionStorage.setItem(
              "all-types",
              JSON.stringify(res.data)
            );
          }
        });
      } else {
        allTypes.value = sessionAllTypes;
      }
    }
    let dataForm: Data = reactive({
      typeId: 0, // 类型Id
      typeName: "", // 类型名称
      value: 0, // 值
      typeUnit: "", // 类型单位
      timestamp: new Date().getTime(), // 时间戳
      date: new Date().toLocaleDateString(), //日期字符串
    });
    let formBindType = ref(null);
    function typeChange(e: any) {
      formBindType.value = e;
      dataForm.typeId = e.id;
      dataForm.typeName = e.name;
      dataForm.typeUnit = e.unit;
    }
    const formLogic = {
      dataFormRef,
      dataForm,
      submitData,
      allTypes,
      formBindType,
      typeChange,
      rules,
    };

    // =====数据展示与删除逻辑=====
    let todayData: Ref<Array<Data>> = ref([]);
    function fetchSelectedDateData(date: Date) {
      // 数据获取
      listDataOneDay({ date: date }).then((res) => {
        console.log(res);
        todayData.value = res.data;
      });
    }
    onMounted(() => {
      fetchSelectedDateData(new Date());
    });
    function deleteDataByID(id: number) {
      // 数据删除
      deleteData(id).then((res) => {
        fetchSelectedDateData(selectedDate.value);
      });
    }
    const listLogic = { todayData, deleteDataByID };

    return {
      ...getDataLogic,
      ...dialogLogic,
      ...formLogic,
      ...listLogic,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "../util/util.scss";
.plus-btn {
  @include plus-btn;
}
</style>